<template>
  <div class="search">
    <van-nav-bar left-arrow title="商品搜索" @click-left="$router.back()" />
    <div class="ser-bott">
      <van-search
        ref="search"
        v-model="search"
        placeholder="请输入搜索的商品"
        show-action
        @search="goSearch"
      >
        <template #action>
          <div @click="goSearch(search)">搜索</div>
        </template>
      </van-search>
    </div>
    <div class="histor">
      <div class="his-top">
        <div class="his-lift">最近搜索</div>
        <van-icon name="delete-o" @click="clear" />
      </div>
      <div class="list">
        <div
          v-for="item in history"
          :key="item"
          class="list-item"
          @click="goSearch(item)"
        >
          {{ item }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getHistoryList, setHistoryList } from '@/utils/storage'

export default {
  name: 'searchCom',
  components: {},
  data () {
    return {
      search: '',
      history: getHistoryList()
    }
  },
  computed: {},
  mounted () {
    this.$nextTick(() => {
      this.$refs.search.querySelector('input').focus()
    })
  },
  methods: {
    goSearch (key) {
      const index = this.history.indexOf(key)
      if (index !== -1) {
        this.history.splice(index, 1)
      }
      this.history.unshift(key)
      setHistoryList(this.history)
      this.$router.push(`/searchlist?search=${key}`)
    },
    clear () {
      this.history = []
      setHistoryList([])
      this.$toast.success('清空历史成功')
    }
  },
  created () {}
}
</script>
<style lang="less">
.search {
  .van-search__action {
    background-color: red;
    color: white;
    width: 70px;
    margin-right: 10px;
    text-align: center;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
  }

  .histor {
    .his-top {
      padding: 20px;
      display: flex;
      justify-content: space-between;
    }

    .list {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      padding: 0 10px;
      gap: 5%;

      .list-item {
        width: 30%;
        text-align: center;
        padding: 7px;
        line-height: 15px;
        border-radius: 50px;
        background: #fff;
        font-size: 13px;
        border: 1px solid #efefef;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin-bottom: 10px;
      }
    }
  }
}
</style>
